package com.demo.autotest.service;

import com.demo.autotest.common.utils.FileUtils;
import com.demo.autotest.database.domain.*;
import com.demo.autotest.database.mapper.*;
import com.demo.autotest.dto.TestFileDTO;
import com.demo.autotest.request.QueryRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Service    // 定义service层
@Transactional(rollbackFor = Exception.class)
public class TestFileService {

    @Resource
    private TestFileMapper testFileMapper;

    @Value("test.file.path")
    private String FILE_PATH;

    public void upload(MultipartFile file, TestFile testFile){
        // 保存文件到数据库中
        testFile.setId(UUID.randomUUID().toString());
        testFile.setUpdateUser(testFile.getCreateUser());
        testFile.setCreateTime(System.currentTimeMillis());
        testFile.setUpdateTime(System.currentTimeMillis());

        String dir_path = FILE_PATH +"/"+testFile.getProjectId()+"/"+testFile.getId();
        FileUtils.saveFile(file, dir_path, file.getOriginalFilename());
        testFile.setFilePath(dir_path + "/" + file.getOriginalFilename());
        testFileMapper.insert(testFile);
    }

    public void delete(String id){
        String filePath = testFileMapper.getTestFileById(id);
        FileUtils.deleteFile(filePath);
        testFileMapper.delete(id);
    }

    public List<TestFileDTO> getTestFileList(QueryRequest request){
        if(request.getCondition() != null && !request.getCondition().equals("")){
            request.setCondition("%" + request.getCondition() + "%");
        }
        return testFileMapper.getTestFileList(request);
    }

}
